<script lang="ts" setup>
import type { Recordable } from '@vben/types';

import { nextTick, onMounted, reactive, ref } from 'vue';
import { useRouter } from 'vue-router';

import { useFs } from '@fast-crud/fast-crud';

import { getValidateRulesByFs } from '#/api/common/validateByFs';
import { DefDictConfig } from '#/api/devOperation/system/defDict';
import { ActionEnum } from '#/enums/commonEnum';
import { useMessage } from '#/hooks/web/useMessage';

import { createCrudOptions, frontRules } from './data/crud';

defineOptions({
  name: '字典项管理',
  inheritAttrs: false,
});
const { currentRoute } = useRouter();
const { createMessage } = useMessage();
const parentIdRef = ref();
const dict = reactive<Recordable>({
  id: '',
  name: '',
  key: '',
  remark: '',
});
const { crudRef, crudBinding, crudExpose, appendCrudOptions } = useFs({
  createCrudOptions,
  context: { parentIdRef },
});

// 页面打开后获取列表数据
onMounted(async () => {
  const addFormOptions = await getValidateRulesByFs({
    Api: DefDictConfig.Save,
    mode: ActionEnum.ADD,
    customRules: frontRules.addForm.rules(crudExpose),
    trigger: ['blur', 'change'],
  });
  const editFormOptions = await getValidateRulesByFs({
    Api: DefDictConfig.Update,
    mode: ActionEnum.EDIT,
    customRules: frontRules.editForm.rules(crudExpose),
    trigger: ['blur', 'change'],
  });
  appendCrudOptions({ ...addFormOptions, ...editFormOptions });

  const { params, query } = currentRoute.value;

  if (params?.dictId) {
    parentIdRef.value = params?.dictId as string;
    dict.id = params?.dictId as string;
    dict.name = (query?.name || '') as string;
    dict.key = (query?.key || '') as string;
    dict.remark = (query?.remark || '') as string;

    // crudExpose.setSearchFormData({ form: { parentId: params?.dictId } });
    await crudExpose.doRefresh();
    await nextTick();
    // crudExpose.setFormData({ parentId: params?.dictId });
  } else {
    createMessage.warning('请传递正确的字典ID');
  }
});
</script>

<template>
  <FsPage>
    <template #header>
      <div class="title">
        {{ `字典【${dict.key}】-【${dict.name}】的字典项` }}
      </div>
    </template>
    <FsCrud ref="crudRef" v-bind="crudBinding" />
  </FsPage>
</template>
